/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
/**
 * @desc 用户权限相关业务
 * @fileName user-permission.ts
 * @author 592107303@qq.com
 * @date 2022-4-27
 */
import http from "./common/http";
import { getCurrentUser } from "./user";

const USER_MENU_KEYS: string = "user_menu_keys";

const getAllPermissions = async () => {
  return new Promise((resolve, reject) => {
    http
      .get({
        url: "/permission",
      })
      .then((r: any) => {
        resolve(r.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * 获取用户菜单权限
 * @returns menuKey的数组
 */
const getMenuPermissions = async (
  doesSaveInCache: boolean = true
): Promise<string[]> => {
  const user = getCurrentUser();
  let list: string[] = [];
  if (user && !user.isAdmin) {
    try {
      const allList: any = await getAllPermissions();
      if (user.isChief) {
        list = Array.from(new Set(allList.map((x: any) => x.menuUrl)));
      } else {
        const userList: any = await http.get({
          url: "/personal/permission",
        });
        console.log("userList", userList.data);
        let urlList: string[] = [];
        userList.data.forEach((userPermissionItem: any) => {
          let permissionItem = allList.find(
            (x: any) => x.id == userPermissionItem.id
          );
          if (permissionItem) {
            urlList.push(permissionItem);
          }
        });
        console.log("urlList", urlList);
        list = Array.from(new Set(urlList.map((x: any) => x.menuUrl)));
      }
    } catch (error) {
      console.log("catch", error);
    }
  }
  if (doesSaveInCache) {
    localStorage.setItem(USER_MENU_KEYS, JSON.stringify(list));
  }
  return list;
};

const getMenuPermissionsFromCache = (): string[] => {
  let value: string = localStorage.getItem(USER_MENU_KEYS) || "";
  if (value) {
    return JSON.parse(value);
  }
  return [];
};

const clearMenuPermissionsCache = () => {
  localStorage.setItem(USER_MENU_KEYS, "");
};

export {
  getAllPermissions,
  getMenuPermissions,
  getMenuPermissionsFromCache,
  clearMenuPermissionsCache,
};
